// // background.js
// let host = null;
// let access_token = null;
// let headers = {
// 	"accept": "application/json, text/plain, */*",
// 	"accept-language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
// 	"content-type": "application/json;charset=UTF-8",
// 	"priority": "u=1, i",
// 	"sec-fetch-dest": "empty",
// 	"sec-fetch-mode": "cors",
// 	"sec-fetch-site": "same-origin",
// 	"x-requested-with": "1729565845731"
// }
// 定义菜单结构
const menuList = [{
	id: "1",
	title: "Tools",
	parentId: null, // 顶级菜单项的parentId为null
	contexts: [
		"all"
	],
	children: [{
		id: "registerPatient",
		title: "使用该名称: %s 创建患者",
		parentId: "1", // 子菜单项的parentId是父菜单项的id
		contexts: [
			"selection"
		]
	},
	{
		id: "deletePatient",
		title: "删除当前患者",
		parentId: "1",
		contexts: [
			"all"
		]
	},
	{
		id: "downloadForm",
		title: "下载当前表单",
		parentId: "1",
		contexts: [
			"all"
		]
	},
	{
		id: "onloadForm",
		title: "批量上传表单",
		parentId: "1",
		contexts: [
			"all"
		]
	},
	{
		id: "autoDelay",
		title: "触发自动顺延",
		parentId: "1",
		contexts: [
			"all"
		]
	},

	],
}
	// 可以添加更多的顶级菜单项
];

function createMenu(menu) {
	chrome.contextMenus.create({
		id: menu.id,
		title: menu.title,
		contexts: menu.contexts, // 指定菜单项显示的上下文，例如："selection"表示选中文本时显示
		parentId: menu.parentId, // 父菜单项的id
	}, function () {
		if (chrome.runtime.lastError) {
			console.log(chrome.runtime.lastError); // 处理创建过程中的错误
		}
		// 如果有子菜单项，递归创建
		if (menu.children && menu.children.length > 0) {
			menu.children.forEach(createMenu);
		}
	});
};

// 遍历菜单结构数组，创建所有菜单项
menuList.forEach(createMenu);

async function sendRequestToTab(requests, parseResponse = (response) => {
	console.log("Received response from content script:", response.msg);
}) {
	chrome.tabs.query({
		active: true,
		currentWindow: true
	}, function (tabs) {
		chrome.tabs.sendMessage(tabs[0].id, requests, function (response) {
			if (chrome.runtime.lastError) {
				console.log("Error:", chrome.runtime.lastError);
			} else {
				parseResponse(response);
			}
		})
	})
};

async function injectScriptToTab(requests, script = () => {
	console.log("代码注入")
}) {
	chrome.tabs.query({
		active: true,
		currentWindow: true
	}, function (tabs) {
		chrome.scripting.executeScript({
			target: {
				tabId: tabs[0].id
			},
			function() {
				script();
			}
		})
	})
};

chrome.contextMenus.onClicked.addListener(function (info, tab) {
	switch (info.menuItemId) {
		case 'registerPatient':
			sendRequestToTab({
				"action": info.menuItemId,
				data: {
					"name": info.selectionText
				}
			});
			break;
		case 'deletePatient':
			sendRequestToTab({
				"action": info.menuItemId,
			});
			break;
		case 'downloadForm':
			sendRequestToTab({
				"action": info.menuItemId
			});
			break;
		case 'onloadForm':
			sendRequestToTab({
				"action": info.menuItemId
			});
			break;
		case 'autoDelay':
			sendRequestToTab({
				"action": info.menuItemId
			}, (res) => {
				autoDelay(res.data.host, res.data.access_token)
			})
			break;
	}
});

async function autoDelay(host, access_token) {
	var body = JSON.stringify({
		"action_client_code": "PC",
		"hospital_code": "HOSPITSDZL0018465465",
		"access_token": access_token,
		"action_user_code": "USER2020042101",
		"action_user_name": "超级管理员"
	})
	var headers = {
		"accept": "application/json, text/plain, */*",
		"accept-language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
		"content-type": "application/json;charset=UTF-8",
		"priority": "u=1, i",
		"sec-fetch-dest": "empty",
		"sec-fetch-mode": "cors",
		"sec-fetch-site": "same-origin",
		"x-requested-with": "1729565845731"
	};

	headers["Cookie"] = `Manteia-access_token=${access_token}`;

	await fetch(`http://${host}:5616/patient_apply_auto_delay`, {
		method: 'POST',
		headers: headers,
		body: body,
		redirect: 'follow'
	})
		.then(response => response.json())
		.then(result => console.log(result))
		.catch(error => console.error('Error：', error));
};